(function (window) {
    var Vue = window.Vue,
        $ = window.$ || window.jQuery,
        baseRequest = window.baseRequest; //  请求
    //  获取所有的设备
    var getDevicesUrl = window.appConfig.v3ServiceUrl + '/ace/oasis/oasis-rest-shop/restshop/shopModel/shopdevices2/';
    //  获取设备列表
    var postDevStatus = window.appConfig.baseServiceUrl + '/getDevs';

    function getDevErr(code, data) {
        var me = this;
        if (data === 'abort') return; //  如果是取消的，就直接不显示弹窗了
        $.confirm(me.$t('base.err.getDev'), '', [me.$t('base.no'), me.$t('base.yes')], function (ok) {
            if (ok.index === 1) { // 是
                initDeviceInfo.call(me);
            } else {
                plus.webview.close(me.webview);
                me.$emit('error', data);
            }
        });
    }

    function initDeviceInfo() {
        // console.log('开始加载设备：' + $.util.formatDate(new Date(), 'y-M-d H:m:s'));
        var me = this;
        // 在请求之前将存储的devSN置空,防止页面使用上次的devSN获取数据
        me.devsn = '';
        me.devsXHR = baseRequest.commonGet(getDevicesUrl + me.shopid, function (code, data) {
            if (code === 2 || code === 1 || data.code !== 0) {
                getDevErr.call(me, code, data);
            } else {
                // console.log('设备加载成功：' + $.util.formatDate(new Date(), 'y-M-d H:m:s'));
                var devObj = {};
                data.data.forEach(function (g) {
                    g.devices.forEach(function (d) {
                        devObj[d.devSn] = d.devAlias;
                    });
                });

                // 获取设备在线状态
                me.statusXHR = baseRequest.commonPost(postDevStatus, JSON.stringify({
                    devSN: Object.keys(devObj)
                }), 50000, function (code, data) {
                    if (code === 2 || code === 1) {
                        //  状态获取失败了
                        me.devsn = Object.keys(devObj).length ? Object.keys(devObj)[0] : null;
                        //  获取状态失败了不拼接在线状态
                        me.devObj = devObj;
                        // console.log('设备状态加载失败：' + $.util.formatDate(new Date(), 'y-M-d H:m:s'));
                    } else {
                        // console.log('设备状态加载成功：' + $.util.formatDate(new Date(), 'y-M-d H:m:s'));
                        /**
                         * 请求状态成功了，就会将设备状态拼接到设备别名的后面   0=在线  非0=不在线
                         */
                        var detail = data.detail;
                        Object.keys(devObj).forEach(function (d) {
                            detail.forEach(function (status) {
                                if (d === status.devSN) {
                                    devObj[d] = devObj[d] + '(' + (status.status !== 0 ? me.$t('base.offline') : me.$t('base.online')) + ')';
                                }
                            });
                        });
                        //  默认选择第一个
                        me.devsn = Object.keys(devObj).length ? Object.keys(devObj)[0] : null;
                        //  初始化
                        me.devObj = devObj;
                    }
                });
            }
        });
    }

    function openDeviceListView() {
        var shopId = this.shopid;
        $.plusReady(function () {
            window.commonTool.openWindow("../common/device/devicelist-main.html", "devicelist-main.html", {
                parentViewId: plus.webview.currentWebview().id,
                shopId: shopId
            });
        });

    }

    function abort() {
        this.devsXHR && this.devsXHR.abort();
        this.statusXHR && this.statusXHR.abort();
    }

    var factory = {
        props: ['shopid'],
        template: ['<header class="mui-bar mui-bar-nav">',
            '<a class="mui-icon mui-icon-left-nav mui-pull-left" @tap.stop="close()"></a>',
            '<h1 class="mui-title" v-text="devObj[devsn] || $t(\'base.noDev\')"></h1>',
            '<div class="header-select-box">',
            '<select class="mui-select header-select" v-model="devsn">',
            '<option v-for="(text,sn) in devObj" :value="sn" v-text="text"></option>',
            '</select>',
            '</div>',
            '<a class="mui-icon mui-icon-bars mui-pull-right" @tap.stop="openDeviceListView()"></a>',
            '</header>'
        ].join(''),
        data: function () {
            return {
                devsn: '',
                devObj: {},
                devsXHR: null,
                statusXHR: null,
                webview: null, //  当前的webview，请求失败的时候关闭当前webview
                listChange: null //  设备列表改变事件，删除设备或者新增设备的时候触发
            };
        },
        mounted: function () {
            $.plusReady(function () {
                if (this.shopid) {
                    // console.log('plusReady开始请求：' + $.util.formatDate(new Date(), 'y-M-d H:m:s'));
                    initDeviceInfo.call(this);
                }
                this.webview = plus.webview.currentWebview();
            }.bind(this));

            this.listChange = function () {
                console.log('设备列表发生了变化');
                if (this.shopid) {
                    initDeviceInfo.call(this);
                }
            }.bind(this);

            window.addEventListener('reloaddevlist', this.listChange);
        },
        beforeDestroy: function () {
            if (this.listChange) {
                window.removeEventListener('reloaddevlist', this.listChange);
            }
            this.listChange = null;
            this.webview = null;
            this.devObj = {};
            this.devsn = '';
        },
        watch: {
            devsn: function (v, v2) {
                // console.log('设备序列号发生了变化：' + $.util.formatDate(new Date(), 'y-M-d H:m:s'));
                if (v && v !== 'undefined') {
                    $.util.setDevSN(v);
                    this.$emit('change', v);
                }
            },
            shopid: function (v) {
                if (v) {
                    $.plusReady(initDeviceInfo.bind(this));
                }
            }
        },
        methods: {
            openDeviceListView: openDeviceListView,
            close: $.back,
            abort: abort
        }
    };

    Vue.component('scene-header', factory);
})(window);